<template>
  <div class="app-container">
    <div class="customContainer oneSearchNoFooter">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select
            filterable
            placeholder="选择门店"
            v-model="formInline.store_id"
            @change="storeChange"
          >
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable v-model="formInline.type" @change="typeChange">
            <el-option label="会员卡充值办理" value="2"></el-option>
            <el-option label="缴费办卡" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.name"
            placeholder="请输入套餐名称"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
        <el-form-item class="pull-right">
          <el-button
            v-if="this.formInline.type==2"
            type="primary"
            @click="rechargeAddEdit()"
          >新增充值办卡套餐</el-button>
          <el-button v-if="this.formInline.type==3" type="primary" @click="addEditClick()">新增缴费办卡套餐</el-button>
        </el-form-item>
      </el-form>
      <transition name="fade" mode="out-in" :key="formInline.type">
        <!-- 表格1 -->
        <div v-if="formInline.type==2">
          <el-table
            highlight-current-row
            :data="list"
            v-loading.body="listLoading"
            border
            size="small"
          >
            <el-table-column align="center" label="序号" width="50">
              <template slot-scope="scope">
                <span class="indexColor">{{scope.$index+1}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="套餐名称" width="280">
              <template slot-scope="scope">
                <el-button type="text" @click="rechargeAddEdit(scope.row,1)">{{scope.row.name}}</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" label="适用门店">
              <template slot-scope="scope">
                {{ scope.row.store_list[0]?scope.row.store_list[0].name:'无'}}
                {{ scope.row.store_list[1]?'，'+scope.row.store_list[1].name:''}}
                {{ scope.row.store_list[2]?'，'+scope.row.store_list[2].name+'...':''}}
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="320">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="rechargeAddEdit(scope.row)"
                ></el-button>
                <el-button
                  type="success"
                  size="mini"
                  v-if="scope.row.is_enable==1"
                  @click="enableClick(scope.row)"
                >已启用</el-button>
                <el-button size="mini" v-else @click="enableClick(scope.row)">已停用</el-button>
                <el-button
                  @click="delClick(scope.row.id,scope.$index)"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                ></el-button>
                <el-button
                  type="primary"
                  plain
                  size="mini"
                  @click="deployStoreClick(scope.row)"
                >配置门店</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 表格2 -->
        <el-table
          highlight-current-row
          v-else
          :data="list"
          v-loading.body="listLoading"
          border
          size="small"
        >
          <el-table-column align="center" label="套餐名称" width="280">
            <template slot-scope="scope">
              <el-button type="text" @click="addEditClick(scope.row)">{{scope.row.name}}</el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="适用门店">
            <template slot-scope="scope">
              {{ scope.row.store_list[0]?scope.row.store_list[0].name:'无'}}
              {{ scope.row.store_list[1]?'，'+scope.row.store_list[1].name:''}}
              {{ scope.row.store_list[2]?'，'+scope.row.store_list[2].name+'...':''}}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="card_name" label="卡类型" width="150"></el-table-column>
          <el-table-column align="center" prop="money" label="办卡金额" width="150"></el-table-column>
          <!-- <el-table-column align="center" prop="give" label="办卡得币/次数/星星数"></el-table-column>
                    <el-table-column align="center" label="生效时间" width="262">
                        <template slot-scope="scope">
                            {{ scope.row.effect_time+' - '+scope.row.stop_time }}
                        </template>
          </el-table-column>-->
          <el-table-column align="center" label="操作" width="320">
            <template slot-scope="scope">
              <el-button
                type="success"
                size="mini"
                v-if="scope.row.is_enable==1"
                @click="enableClick(scope.row)"
              >已启用</el-button>
              <el-button size="mini" v-else @click="enableClick(scope.row)">已停用</el-button>
              <el-button
                @click="delClick(scope.row.id,scope.$index)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
              <el-button type="primary" plain size="mini" @click="deployStoreClick(scope.row)">配置门店</el-button>
            </template>
          </el-table-column>
        </el-table>
      </transition>
      <!-- 新增充值弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        width="390px"
        :title="rechargeDialogTitle"
        :visible.sync="rechargeDialog"
        append-to-body
        @close="callOf('rechargeForm')"
      >
        <el-form
          :model="rechargeForm"
          :rules="rechargeRules"
          ref="rechargeForm"
          class="demo-form-inline"
        >
          <el-form-item label="套餐名称" prop="name">
            <el-input
              :disabled="is_edit"
              :maxlength="20"
              onkeypress="return event.which!=32"
              placeholder="请输入套餐名称(二十字内)"
              v-model="rechargeForm.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="临时卡" prop="temp_min_money">
            <el-input
              :disabled="is_look"
              placeholder="请输入正确金额"
              onkeypress="return event.which<=57"
              v-model="rechargeForm.temp_min_money"
            ></el-input>
          </el-form-item>
          <el-form-item label="会员卡" prop="normal_min_money">
            <el-input
              :disabled="is_look"
              placeholder="请输入正确金额"
              onkeypress="return event.which<=57"
              v-model="rechargeForm.normal_min_money"
            ></el-input>
          </el-form-item>
          <el-form-item label="精英会员卡" prop="elite_min_money">
            <el-input
              :disabled="is_look"
              placeholder="请输入正确金额"
              onkeypress="return event.which<=57"
              v-model="rechargeForm.elite_min_money"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="!is_look"
            type="primary"
            @click="rechargeSaveClick('rechargeForm')"
            size="small"
          >保存配置</el-button>
        </div>
      </el-dialog>
      <!-- 套餐新增编辑弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        width="420px"
        :title="is_look&&formInline.type==3?'套餐详情':formInline.type==2?'新增充值套餐':'新增缴费办卡套餐'"
        :visible.sync="addEditDialog"
        append-to-body
        @close="callOf('saveForm')"
      >
        <el-form :model="saveForm" :rules="rules" ref="saveForm" class="demo-form-inline">
          <el-form-item style="display: inline-block">
            <el-checkbox
              :disabled="is_look"
              v-model="saveForm.is_re"
              @change="relatedChange"
            >关联第三方商品</el-checkbox>
          </el-form-item>
          <el-form-item
            v-if="saveForm.is_re"
            prop="is_collect"
            style="width:125px; display: inline-block"
          >
            <el-select :disabled="is_look" size="mini" filterable v-model="saveForm.is_collect">
              <el-option
                v-for="item in related_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="saveForm.is_re&&saveForm.is_collect*1<3"
            prop="product_id"
            style="width:125px; display: inline-block"
          >
            <el-input
              :disabled="is_look"
              size="mini"
              placeholder="输入商品ID"
              v-model="saveForm.product_id"
            ></el-input>
          </el-form-item>
          <el-form-item label="套餐名称" prop="name">
            <el-input
              :disabled="is_look"
              :maxlength="20"
              onkeypress="return event.which!=32"
              placeholder="请输入套餐名称(二十字内)"
              v-model="saveForm.name"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="is_look" label="类型" prop="type_id">
            <el-input :disabled="is_look" v-model="saveForm.card_name"></el-input>
          </el-form-item>
          <el-form-item v-else label="类型" prop="type_id">
            <el-select
              :disabled="is_look"
              filterable
              v-model="saveForm.type_id"
              style="width:380px;"
              @change="typeIdChange"
            >
              <el-option
                v-for="item in type_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="办卡金额" prop="money">
            <el-input
              :disabled="is_look"
              placeholder="请输入办卡金额"
              onkeypress="return event.which<=57"
              v-model="saveForm.money"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="saveForm.type_id==11" label="获得次数" prop="times">
            <el-input
              :disabled="is_look"
              placeholder="请输入次数"
              onkeypress="return event.which>=48&&event.which<=57"
              v-model="saveForm.times"
            ></el-input>
          </el-form-item>
          <el-form-item label="生效日期" prop="pickerDate">
            <el-date-picker
              :disabled="is_look"
              v-model="saveForm.pickerDate"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              style="width:380px;"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            :label="give_label"
            v-if="saveForm.type_id==0||saveForm.type_id==1||saveForm.type_id==2||saveForm.type_id==3||saveForm.type_id==8"
          >
            <el-input
              :disabled="is_look"
              placeholder="非必填"
              min="0"
              type="number"
              onmousewheel="return false;"
              v-model="saveForm.coins"
            ></el-input>
          </el-form-item>
        </el-form>

        <div v-if="!is_look" slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveClick('saveForm')" size="small">保存配置</el-button>
        </div>
      </el-dialog>

      <!-- 配置门店弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        width="650px"
        title="选择门店"
        :visible.sync="storeDialog"
      >
        <div v-if="storeDialog">
          <div class="el-transfer-panel pull-left transferHeader">选择门店</div>
          <div class="el-transfer-panel pull-right transferHeader">已选门店</div>
        </div>
        <el-transfer
          :props="{key: 'id', label: 'name'}"
          :titles="['全选', '全选']"
          :button-texts="['删除', '添加']"
          filterable
          v-model="check_store_list"
          :data="t_store_list"
          ref="transfer"
          :left-default-checked="leftChecked"
          :right-default-checked="rightChecked"
          @change="checkStoreChange"
        ></el-transfer>
        <span slot="footer" class="dialog-footer">
          <el-button :disabled="btnDisabled" size="small" type="primary" @click="saveStoreClick">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getList,
  getStoreList,
  save_card_renewal,
  enable_card_renewal,
  savePackage,
  del,
  saveStore,
} from "@/api/member/rechargeCard";
import { money, nullto999999 } from "@/utils/validate";
import { pickerOptionsAfterF } from "@/utils";
export default {
  data() {
    const validateVal = (rule, value, callback) => {
      if (!money(value)) {
        callback(new Error("请输入正确的金额"));
      } else {
        callback();
      }
    };
    return {
      list: null,
      storeDialog: false,
      rechargeDialog: false,
      addEditDialog: false,
      btnDisabled: true,
      is_edit: false,
      is_look: false,
      listLoading: false,
      rechargeDialogTitle: "",
      give_label: "办卡充值币数",
      related_list: [
        { id: "1", name: "关联快盈 " },
        { id: "2", name: "关联口碑" },
        { id: "3", name: "代收待核" },
      ],
      type_list: [
        { id: "1", name: "临时卡" },
        { id: "2", name: "普通会员卡" },
        { id: "3", name: "精英会员卡" },
        { id: "4", name: "10次卡" },
        { id: "5", name: "20次卡" },
        { id: "6", name: "季卡" },
        { id: "7", name: "年卡" },
        { id: "8", name: "星星卡" },
        { id: "9", name: "6次卡" },
        { id: "10", name: "12次卡" },
        { id: "11", name: "E舞成名卡" },
        { id: "12", name: "月卡" },
      ],
      storeList: null,
      formInline: {
        store_id: "",
        type: "2",
        name: "",
      },
      rechargeForm: {
        name: "",
        temp_min_money: "",
        normal_min_money: "",
        elite_min_money: "",
        type: "",
        id: "",
      },
      saveForm: {
        name: "",
        type: "",
        money: "",
        coins: "",
        effect_time: "",
        times: "",
        stop_time: "",
        pickerDate: [],
        type_id: "",
        is_re: "",
        product_id: "",
        is_collect: "",
        card_name: "",
      },
      saveStore: {
        store_list: [],
        id: "",
        type: "",
      },
      t_store_list: [],
      check_store_list: [],
      leftChecked: [],
      rightChecked: [],
      rechargeRules: {
        name: [{ required: true, message: "请输入套餐名称", trigger: "blur" }],
        temp_min_money: [
          { required: true, validator: validateVal, trigger: "blur" },
        ],
        normal_min_money: [
          { required: true, validator: validateVal, trigger: "blur" },
        ],
        elite_min_money: [
          { required: true, validator: validateVal, trigger: "blur" },
        ],
      },
      rules: {
        is_collect: [
          { required: true, message: "请选中关联类型", trigger: "change" },
        ],
        product_id: [
          { required: true, message: "请输入商品ID", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入套餐名称", trigger: "blur" }],
        type_id: [
          { required: true, message: "请选择卡类型", trigger: "change" },
        ],
        times: [{ required: true, message: "请填写次数", trigger: "blur" }],
        money: [{ required: true, validator: validateVal, trigger: "blur" }],
        pickerDate: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
      },
      pickerOptions: pickerOptionsAfterF(),
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (!vm.storeList) {
        vm.getStore();
      }
    });
  },
  methods: {
    relatedChange() {},
    deployStoreClick(row) {
      this.t_store_list = this.storeList.filter(
        (item) => item.name !== "全门店"
      );
      this.btnDisabled = false;
      this.storeDialog = true;
      this.rightChecked = [];
      this.leftChecked = [];
      setTimeout(() => {
        this.$refs.transfer.clearQuery("left");
        this.$refs.transfer.clearQuery("right");
      }, 0);
      this.saveStore.id = row.id;
      this.saveStore.type = this.formInline.type;
      this.check_store_list = row.store_list.map((val) => val.id);
    },
    saveStoreClick() {
      //
      this.saveStore.store_list = JSON.parse(
        JSON.stringify(this.check_store_list)
      );
      saveStore(this.saveStore)
        .then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          this.fetchData();
          this.storeDialog = false;
        })
        .catch((err) => {
          if (err.code) {
            this.btnDisabled = true;
            this.$message({
              type: "error",
              message: "部分所选门店已配置充值套餐，请勿重复配置，请删除",
              duration: 5 * 1000,
            });
            this.rightChecked = err.list;
          }
        });
    },
    checkStoreChange() {
      this.btnDisabled = false;
      // console.log(this.check_store_list)
    },
    rechargeSaveClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.rechargeForm.type = this.formInline.type;
          save_card_renewal(this.rechargeForm).then((response) => {
            this.$message({
              type: response.code == 1 ? "success" : "error",
              message: response.message,
            });
            if (response.code == 1) {
              this.fetchData();
              this.rechargeDialog = false;
            }
          });
        }
      });
    },
    rechargeAddEdit(row, look) {
      this.rechargeDialog = true;
      this.rechargeDialogTitle = row
        ? look
          ? "套餐详情"
          : "修改充值套餐"
        : "新增充值套餐";
      this.is_look = look ? true : false;
      this.is_edit = row ? true : false;
      this.rechargeForm.name = row ? row.name : "";
      this.rechargeForm.temp_min_money = row ? row.temp_min_money : "";
      this.rechargeForm.normal_min_money = row ? row.normal_min_money : "";
      this.rechargeForm.elite_min_money = row ? row.elite_min_money : "";
      this.rechargeForm.id = row ? row.id : "";
    },
    typeIdChange() {
      if (
        this.saveForm.type_id == 4 ||
        this.saveForm.type_id == 5 ||
        this.saveForm.type_id == 6 ||
        this.saveForm.type_id == 7 ||
        this.saveForm.type_id == 9 ||
        this.saveForm.type_id == 10
      ) {
        this.saveForm.coins = "";
      } else if (this.saveForm.type_id == 8) {
        this.give_label = "办卡送星星";
      } else {
        this.give_label = "办卡充值币数";
      }
      if (this.saveForm.type_id != 11) {
        this.saveForm.times = "";
      }
    },
    addEditClick(row) {
      this.addEditDialog = true;
      this.is_look = row ? true : false;
      this.saveForm.name = row ? row.name : "";
      this.saveForm.money = row ? row.money : "";
      this.saveForm.coins = row ? row.coins : "";
      this.saveForm.times = row ? row.times : "";
      this.saveForm.type_id = row ? row.type_id : "";
      this.saveForm.product_id = row ? row.product_id : "";
      this.saveForm.is_re = row && row.is_collect > 0 ? true : false;
      this.saveForm.is_collect = row ? row.is_collect + "" : "";
      this.saveForm.pickerDate = row ? [row.effect_time, row.stop_time] : [];
      this.saveForm.card_name = row ? row.card_name : "";
    },
    // 新增提交
    saveClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!nullto999999(this.saveForm.coins)) {
            this.$message({ type: "error", message: "币数只能为0-999999整数" });
            return;
          }
          this.saveForm.effect_time = this.saveForm.pickerDate[0];
          this.saveForm.stop_time = this.saveForm.pickerDate[1];
          this.saveForm.type = this.formInline.type;
          if (!this.saveForm.is_re) {
            this.is_collect = 0;
          }
          let data = JSON.parse(JSON.stringify(this.saveForm));
          savePackage(data).then((response) => {
            this.fetchData();
            this.addEditDialog = false;
            this.$message({
              type: response.code == 1 ? "success" : "error",
              message: response.message,
            });
          });
        }
      });
    },
    // 停用启用
    enableClick(row) {
      let text =
        row.is_enable == 1
          ? "是否停用套餐，停用后将立刻生效"
          : "是否启用套餐，启用后将立刻生效";
      this.$confirm(text, "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }).then(() => {
        let data = {
          is_enable: row.is_enable == 1 ? 0 : 1,
          id: row.id,
          type: this.formInline.type,
        };
        enable_card_renewal(data).then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          if (response.code == 1) {
            row.is_enable = row.is_enable == 1 ? 0 : 1;
          }
        });
      });
    },
    delClick(id, index) {
      this.$confirm("确认删除", "提示", { type: "warning" }).then(() => {
        let data = {
          is_del: 1,
          id: id,
          type: this.formInline.type,
        };
        del(data).then((response) => {
          this.$message({
            type: response.code == 1 ? "success" : "error",
            message: response.message,
          });
          if (response.code == 1) {
            this.list.splice(index, 1);
          }
        });
      });
    },
    storeChange() {
      this.fetchData();
    },
    getStore() {
      getStoreList({ category_id: this.$route.meta.id }).then((response) => {
        this.storeList = response;
        let data = response.filter(
          (res) => res.id == this.$store.getters.optionId
        );
        if (data.length > 0) {
          this.formInline.store_id = data[0].id;
        } else {
          if (this.storeList.length > 0) {
            this.formInline.store_id = this.storeList[0].id;
          }
        }
        this.fetchData();
      });
    },
    typeChange() {
      this.fetchData();
    },
    // 搜索
    searchClick() {
      this.fetchData();
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      getList(this.formInline)
        .then((response) => {
          response.forEach((val) => {
            switch (val.type_id) {
              case "0":
                val.card_name =
                  val.card_type_id == 2
                    ? "临时卡"
                    : val.card_type_id == 0
                    ? "普通会员卡"
                    : "精英会员卡";
                val.give = val.coins + "币";
                break;
              case "1":
                val.card_name =
                  val.card_type_id == 10
                    ? "10次卡"
                    : val.card_type_id == 6
                    ? "6次卡"
                    : val.card_type_id == 12
                    ? "12次卡"
                    : "20次卡";
                val.give = val.times + "次";
                break;
              case "2":
                val.card_name = "季卡";
                val.give = "-";
                break;
              case "3":
                val.card_name = "年卡";
                val.give = "-";
                break;
              case "4":
                val.card_name = "星星卡";
                val.give = val.stars + "星";
                break;
              case "5":
                val.card_name = "E舞成名卡";
                val.give = val.times + "次";
                break;
              case "6":
                val.card_name = "月卡";
                val.give = "-";
                break;
              default:
                val.card_name = "未知";
                val.give = "-";
                break;
            }
          });
          this.list = response;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    callOf(formName) {
      this.saveForm.coins = "";
      this.saveForm.is_re = false;
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    "saveForm.product_id": function (val) {
      this.saveForm.product_id = this.saveForm.product_id.replace(
        /^\s+|\s+$/g,
        ""
      );
    },
  },
};
</script>